import _ from "underscore"

var http = {
  ajax:function(options){
    $.ajax(options);
  },
  sendAjax:function(options){
      var params = this.getRequestParams(options.service,options.data);
      //对params进行stringify后 进行加密
      var opt = {
          url:"/symeetingbook/api/",
          type:options.type || "POST",
          data:JSON.stringify(params),
          dataType:"json",
          contentType:"application/x-www-form-urlencoded",
          timeout:10000,
          success:function(res){
              //parse成json
              try {
                if(typeof res == "string"){
                    res = JSON.parse(res);
                }
                if(res && res.flag == 0){
                    options.success && options.success(res.response);
                }else{
                    //具体信息可能要经过前端优化处理 交给业务具体处理
                    options.error && options.error(res);
                }
              } catch (e) {
                window.R.toast && window.R.toast("请求失败");
                options.error && options.error({});
              }


          },
          error:function(res){
            window.R.toast && window.R.toast("请求失败");
            console.log(res);
            options.error && options.error({});
          }
      };
      this.ajax(opt);
  },
  getRequestParams:function(service,params){
      var staticParams = {
          uid:"",//TODO需要从应用传递uid过来,目前固定死一个
          port:this.getPlatform(),
          appvertion:"63",
          cursize:0,
          requestsize:100,
          // random:""
      }
      for(var key in params){
          staticParams[key] = params[key];
      }
      var data = {
          serverid:{
              method:service
          },
          param:staticParams
      }
      return data;
  },
  getPlatform:function(){
      var u = navigator.userAgent;
      var isiOS = /ipad|iphone|mac/i.test(navigator.userAgent); //ios终端
      if(isiOS) {
          return 0;
      }
      return 1;
  }
}

_.extend(window.application, http);

//测试代码
// var options = {
//   service:"GetAllrooms",
//   data:{},
//   success:function(res){
//       console.log(res);
//   },
//   error:function(err){
//     console.log(err);
//   }
// }
// application.sendAjax(options);
